// DriveNotes. Copyright (c) 2011, Andrei Senchuk. All rights reserved.
package net.taviscaron.drivenotes.server.service;

import net.taviscaron.drivenotes.server.model.dao.UserDAO;
import net.taviscaron.drivenotes.server.model.validators.Validator;
import net.taviscaron.drivenotes.server.util.EncryptionUtil;
import net.taviscaron.drivenotes.server.util.EntityUtils;
import static net.taviscaron.drivenotes.server.util.ExceptionUtils.invalidEntityException;
import net.taviscaron.drivenotes.shared.exceptions.InvalidEntityException;
import net.taviscaron.drivenotes.shared.model.entity.User;
import net.taviscaron.drivenotes.shared.service.RegisterService;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.transaction.annotation.Transactional;

/**
 * Register service
 * @author Andrei Senchuk
 */
public class RegisterServiceImpl implements RegisterService {
    public enum Error {
        SUCH_USERNAME_NA
    }

    private UserDAO userDAO;
    private Validator<User> userValidator;

    @Required
    public void setUserDAO(UserDAO userDAO) {
        this.userDAO = userDAO;
    }

    @Required
    public void setUserValidator(Validator<User> userValidator) {
        this.userValidator = userValidator;
    }

    @Transactional
    public User registerUser(User user) throws InvalidEntityException {
        userValidator.validate(user);

        if(userDAO.findByUsername(user.getUsername()) != null) {
            throw invalidEntityException(Error.SUCH_USERNAME_NA);
        }

        String password = user.getPassword();
        String salt = EncryptionUtil.generateSalt();
        user.setSalt(salt);
        user.setPassword(EncryptionUtil.calculateHash(password, salt));

        userDAO.save(user);

        return EntityUtils.createUserValueObject(user);
    }
}
